package com.sbl.bajw.pc.action;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sbl.bajw.common.ExcelUtil;
import com.sbl.bajw.common.web.JsonResultUtil;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.pc.model.LogScoreModel;
import com.sbl.bajw.pc.service.LogScoreModelService;
import com.sbl.bajw.pc.service.PerformanceTModelService;
import com.sbl.bajw.util.JsonUtil;
import com.sbl.bajw.util.LogUtil;

@Controller
@RequestMapping("/PerformanceTModel")
public class PerformanceTModelAction {
	
	@Resource
	private PerformanceTModelService service;
	
	@Resource
	private LogScoreModelService logService;
	
	static Logger log;
	
	static{
		log = LogUtil.getLogger("Score");
	}
	
	SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 获取个人积分列表
	 */
	@RequestMapping(value = "/getPerformanceTModelList")
	public @ResponseBody String getPerformanceTModelList(HttpServletRequest request, HttpServletResponse response){
		String userId = RequestUnit.getString("user_id");
		String startDate = RequestUnit.getString("start_date");
		String stopDate = RequestUnit.getString("stop_date");
		HashMap<String, Object> parm = new HashMap<String, Object>();
		parm.put("userId", userId);
		if(startDate == null || startDate.equals("")){
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			startDate = sf.format(new Date());
		}
		
		if(stopDate == null || stopDate.equals("")){
			stopDate = startDate;
		}

		parm.put("startDate", startDate+" 00:00:00");
		parm.put("stopDate", stopDate+" 23:59:59");
		//查询数据
		String list = service.statistics(parm);
		
		String json = "";
		json += "{";
		json += "\"code\":\"1\",";
		json += "\"msg\":\"数据加载成功\",";
		json += "\"success\":\"true\",";
		json += "\"data\":"+list+"";
		json += "}";
		return json;
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return APP获取积分
	 */
	@RequestMapping(value = "/getPerformanceListApp")
	public @ResponseBody String getPerformanceListApp(HttpServletRequest request, HttpServletResponse response){
		String userId = RequestUnit.getString("user_id");
		String date = RequestUnit.getString("date");
		HashMap<String, Object> parm = new HashMap<String, Object>();
		parm.put("userId", userId);
		if(date == null || date.equals("")){
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			date = sf.format(new Date());
		}
		
		//查询数据列表
		parm.put("startDate", date + " 00:00:00");
		parm.put("stopDate", date + " 23:59:59");
		String list = service.statistics(parm);
		
		//查询每月，每日，当天的绩效总分
		parm.put("start1", date + " 00:00:00");
		parm.put("stop1", date + " 23:59:59");
		String date1 = date.split("-")[0] + "-" + date.split("-")[1];
		parm.put("start2", date1 + "-01 00:00:00");
		int year = Integer.parseInt(date.split("-")[0]);
		int month = Integer.parseInt(date.split("-")[1]);
		if(year%4 == 0){
			if(month == 2){
				parm.put("stop2", date1 + "-29 23:59:59");
			}else if(month == 4 || month == 6 || month == 9 || month == 11){
				parm.put("stop2", date1 + "-30 23:59:59");
			}else{
				parm.put("stop2", date1 + "-31 23:59:59");
			}
		}else{
			if(month == 2){
				parm.put("stop2", date1 + "-28 23:59:59");
			}else if(month == 4 || month == 6 || month == 9 || month == 11){
				parm.put("stop2", date1 + "-30 23:59:59");
			}else{
				parm.put("stop2", date1 + "-31 23:59:59");
			}
		}
		HashMap<String, String> map = service.getAllScore(parm);
		String result = "{\"score\":" + JsonUtil.ConvertObjectToJson(map) + ",\"list\":" + list + "}";
		
		String json = JsonResultUtil.Success("", result);
		return json;
	}
	
	/**
	 * @作者：罗琦
	 * @return 后台获取总积分
	 */
	@RequestMapping(value = "/getAllScore")
	public @ResponseBody String getAllScore(HttpServletRequest request, HttpServletResponse response){
		String userId = RequestUnit.getString("user_id");
		Date date = new Date();
		HashMap<String, Object> parm = new HashMap<String, Object>();
		parm.put("userId", userId);
		parm.put("start1", sdf0.format(date) + " 00:00:00");
		parm.put("stop1", sdf0.format(date) + " 23:59:59");
		parm.put("start2", sdf1.format(date) + "-01 00:00:00");
		int year = Integer.parseInt(sdf1.format(date).split("-")[0]);
		int month = Integer.parseInt(sdf1.format(date).split("-")[1]);
		if(year%4 == 0){
			if(month == 2){
				parm.put("stop2", sdf1.format(date) + "-29 23:59:59");
			}else if(month == 4 || month == 6 || month == 9 || month == 11){
				parm.put("stop2", sdf1.format(date) + "-30 23:59:59");
			}else{
				parm.put("stop2", sdf1.format(date) + "-31 23:59:59");
			}
		}else{
			if(month == 2){
				parm.put("stop2", sdf1.format(date) + "-28 23:59:59");
			}else if(month == 4 || month == 6 || month == 9 || month == 11){
				parm.put("stop2", sdf1.format(date) + "-30 23:59:59");
			}else{
				parm.put("stop2", sdf1.format(date) + "-31 23:59:59");
			}
		}
		HashMap<String, String> map = service.getAllScore(parm);
		String json = JsonResultUtil.Success("", JsonUtil.ConvertObjectToJson(map));
		return json;
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 积分项分数
	 */
	@RequestMapping(value = "/getLogScore")
	public @ResponseBody String getLogScore(HttpServletRequest request, HttpServletResponse response){
		String list = logService.getLogScore();
		return list;
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 获取单项积分详情
	 */
	@RequestMapping(value = "/getLogScoreModel")
	public @ResponseBody String getLogScoreModel(HttpServletRequest request, HttpServletResponse response){
		String id = RequestUnit.getString("id");
		HashMap<String, Object> parm = logService.getLogScoreModel(id);
		return JsonUtil.ConvertObjectToJson(parm);
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 变更积分项积分
	 * @throws MessageException
	 */
	@RequestMapping(value = "/updateLogScore")
	public @ResponseBody String updateLogScore(HttpServletRequest request, HttpServletResponse response) throws MessageException{
		String id = RequestUnit.getString("id");
		String score = RequestUnit.getString("score");
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			log.info("更新成功：id=" + id + ",score=" + score);
			logService.update(id, score);
			map.put("code", "1");
			map.put("msg", "更新成功");
			map.put("success", "true");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e);
			throw new MessageException("更新出错", "1");
		}
		return JsonUtil.ConvertObjectToJson(map);
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 查询所有人员积分
	 */
	@RequestMapping(value = "/getUserPerformance")
	public @ResponseBody String getUserPerformance(HttpServletRequest request, HttpServletResponse response){
		LogScoreModel score = RequestUnit.getModel(LogScoreModel.class);
		HashMap<String, Object> parm = new HashMap<String, Object>();
		if(score.getUsername() != null && !score.getUsername().equals("")){
			parm.put("username", "%" + score.getUsername() + "%");
		}
		if(score.getUsertype() != null && !score.getUsertype().equals("")){
			parm.put("usertype", score.getUsertype());
		}
		if(score.getStartDate() != null && !score.getStartDate().equals("")){
			String startDate = RequestUnit.getString("startDate");
			parm.put("start_date", startDate + ":00");
		}
		if(score.getStopDate() != null && !score.getStopDate().equals("")){
			String stopDate = RequestUnit.getString("stopDate" + ":59");
			parm.put("stop_date", stopDate);
		}
		if(score.getLogCode() != null && !score.getLogCode().equals("")){
			parm.put("scoreId", score.getLogCode());
		}
		if(score.getPcs() != null && !score.getPcs().equals("")){
			String deptFullId = "0-1-";
			deptFullId += score.getPcs() + "-";
			
			if(score.getJq() != null && !score.getJq().equals("")){
				deptFullId += score.getJq() + "-";
				
				if(score.getZrq() != null && !score.getZrq().equals("")){
					deptFullId += score.getZrq() + "-";
				}
			}
			parm.put("dept", deptFullId);
		}
		log.info("username："+score.getUsername()+"usertype："+score.getUsertype()+"startDate："+score.getStartDate()
				+"stopDate："+score.getStopDate()+"deptfullid："+parm.get("dept"));
		String json = logService.getUserPerformance(parm);
		return json;
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @throws Exception
	 * 导出积分列表
	 */
	@RequestMapping(value = "/downloadUserPerformance")
	public void downloadUserPerformance(HttpServletRequest request, HttpServletResponse response) throws Exception{
		LogScoreModel score = RequestUnit.getModel(LogScoreModel.class);
		HashMap<String, Object> parm = new HashMap<String, Object>();
		if(score.getUsername() != null && !score.getUsername().equals("")){
			parm.put("username", "%" + score.getUsername() + "%");
		}
		if(score.getUsertype() != null && !score.getUsertype().equals("")){
			parm.put("usertype", score.getUsertype());
		}
		if(score.getStartDate() != null && !score.getStartDate().equals("")){
			String startDate = RequestUnit.getString("startDate");
			parm.put("start_date", startDate + ":00");
		}
		if(score.getStopDate() != null && !score.getStopDate().equals("")){
			String stopDate = RequestUnit.getString("stopDate" + ":59");
			parm.put("stop_date", stopDate);
		}
		if(score.getLogCode() != null && !score.getLogCode().equals("")){
			parm.put("scoreId", score.getLogCode());
		}
		if(score.getPcs() != null && !score.getPcs().equals("")){
			String deptFullId = "0-1-";
			deptFullId += score.getPcs() + "-";
			
			if(score.getJq() != null && !score.getJq().equals("")){
				deptFullId += score.getJq() + "-";
				
				if(score.getZrq() != null && !score.getZrq().equals("")){
					deptFullId += score.getZrq() + "-";
				}
			}
			parm.put("dept", deptFullId);
		}
		log.info("username："+score.getUsername()+"usertype："+score.getUsertype()+"startDate："+score.getStartDate()
				+"stopDate："+score.getStopDate()+"deptfullid："+parm.get("dept"));
		List<HashMap<String, Object>> list = logService.downloadUserPerformance(parm);
		HashMap<String, String> column = new HashMap<String, String>();
		column.put("ID", "序号");
		column.put("SHOWNAME", "姓名");
		column.put("SCORE", "总分");
		HSSFWorkbook wb = ExcelUtil.createExcel(list, column);
		OutputStream outStream = response.getOutputStream();
		response.setContentType("application/x-msdownload");  
		response.setHeader("Content-Disposition","attachment;filename=score.xls");  
		wb.write(outStream);
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 获取用户积分详情
	 */
	@RequestMapping(value = "/getUserPerformanceInformation")
	public @ResponseBody String getUserPerformanceInformation(HttpServletRequest request, HttpServletResponse response){
		String id = RequestUnit.getString("id");
		String code = RequestUnit.getString("log_code");
		String start = RequestUnit.getString("start_date");
		String stop = RequestUnit.getString("stop_date");
		HashMap<String, Object> parm = new HashMap<String, Object>();
		String json = null;
		if(id != null && !id.equals("")){
			parm.put("id", id);
			if(code != null && !code.equals("")){
				parm.put("code", code);
			}
			if(start != null && !start.equals("")){
				parm.put("start", start);
			}
			if(stop != null && !stop.equals("")){
				parm.put("stop", stop);
			}
			json = logService.getUserPerformanceInformation(parm);
		}
		return json;
	}
	
	/**
	 * @作者：罗琦
	 * @param request
	 * @param response
	 * @return 通过id查询用户积分
	 */
	@RequestMapping(value = "/getUserPerformanceById")
	public @ResponseBody String getUserPerformanceById(HttpServletRequest request, HttpServletResponse response){
		String id = RequestUnit.getString("user_id");
		List<HashMap<String, Object>> list = logService.getUserPerformanceById(id);
		String json = JsonResultUtil.Success("数据加载成功", JsonUtil.ConvertArrayToJson(list));
		return json;
	}
}
